package com.bkitmobile.kesu.android.GUI;

import org.json.JSONException;
import org.json.JSONObject;

import com.bkitmobile.kesu.android.ClassInfo.UserConfig;
import com.bkitmobile.kesu.android.connectServer.staticClass;
import com.bkitmobile.kesu.android.service.UpdateLocationService;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SettingState extends Activity implements OnCheckedChangeListener{
	CheckBox noPlace, near, favorite;
	private UserConfig uConfig;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_tab_state);
		uConfig = (UserConfig) getIntent().getExtras().getSerializable("config");
		init();
	}
	public void onPause() {
		super.onPause();
		Log.d("Pause", "pause");
	}
	public void onStop() {
		super.onStop();
		JSONObject jObject = new JSONObject();
		try {
			jObject.put("id", "SettingState");
			jObject.put("near", near.isChecked() && near.isEnabled());
			jObject.put("favorite", favorite.isChecked() && favorite.isEnabled());
			Log.d("send", jObject.toString());
			staticClass.socket.println(jObject.toString());
			//save to service
			Bundle data = new Bundle();
			data.putBoolean("near", near.isChecked() && near.isEnabled());
			data.putBoolean("favorite", favorite.isChecked() && favorite.isEnabled());
			Message msg = new Message();
			msg.setData(data);
			msg.what = UpdateLocationService.STATE;
			staticClass.sendToService.sendMessage(msg);
		} catch (JSONException e)
		{
			
		}
		Log.d("Stop", "Stop");
	}
	private void init() {
		noPlace = (CheckBox) findViewById(R.id.setting_tabState_noPlace);
		near = (CheckBox) findViewById(R.id.setting_tabState_near);
		favorite = (CheckBox) findViewById(R.id.setting_tabState_favoritePlace);
		noPlace.setOnCheckedChangeListener(this);
		near.setOnCheckedChangeListener(this);
		favorite.setOnCheckedChangeListener(this);
		if (!(uConfig.isLoadAround()||uConfig.isLoadFavorite()))
		{
			noPlace.setChecked(true);
			setClickAndSelect(noPlace, true);
			setClickAndSelect(near, false);
			setClickAndSelect(favorite, false);
			Log.d("abc", "abc");
		}
		else 
		{
			noPlace.setChecked(false);
			setClickAndSelect(near, true);
			setClickAndSelect(favorite, true);
		}
		near.setChecked(uConfig.isLoadAround());
		favorite.setChecked(uConfig.isLoadFavorite());
		
	}
	
	
	@Override 
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(buttonView == noPlace){
			setClickAndSelect(near, !isChecked);
			setClickAndSelect(favorite, !isChecked);
			
		}
		else if(buttonView == near){
			
		}
		else if(buttonView == favorite){
			
		}
		
	}
	
	private void setClickAndSelect(CheckBox obj, boolean check){
		obj.setEnabled(check);
		obj.setClickable(check);
//		obj.setChecked(false);
	}
	
	
}
